<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>查看排班表</title>
    <link rel="stylesheet" href="../../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f7f7f7;
            color: #333;
        }

        .admin-layout {
            background-color: #f7f7f7;
        }

        .content-wrapper {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 24px;
            margin: 20px;
        }

        .content-header {
            margin-bottom: 24px;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 16px;
        }

        #pageTitle {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        /* iOS风格表单 */
        .form-container {
            max-width: 600px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #666;
            margin-bottom: 8px;
            display: block;
        }

        .required-field::after {
            content: "*";
            color: #dc3545;
            margin-left: 4px;
        }

        .form-control, .form-select {
            height: 44px;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 0 16px;
            font-size: 16px;
            transition: all 0.2s ease;
            width: 100%;
            background-color: #f9f9f9;
        }

        .form-control:focus, .form-select:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
            background-color: #fff;
            outline: none;
        }

        /* 按钮样式 */
        .btn {
            height: 44px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            padding: 0 20px;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: #28a745;
            border-color: #28a745;
        }

        .btn-primary:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }

        .btn-secondary {
            background-color: #f2f2f7;
            border-color: #f2f2f7;
            color: #28a745;
        }

        .btn-secondary:hover {
            background-color: #e5e5ea;
            border-color: #e5e5ea;
        }

        .btn-action {
            min-width: 120px;
        }

        /* 左侧菜单样式 */
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .content-wrapper {
                padding: 16px;
                margin: 10px;
            }

            .form-container {
                padding: 0;
            }
        }
        .submenu {
            display: none;
        }
        .menu-item.active > .submenu {
            display: block;
        }
        .menu-arrow {
            transition: transform 0.2s;
        }
        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        /* 排班表样式 */
        .filter-container {
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .filter-item {
            display: flex;
            align-items: center;
        }

        .filter-item label {
            margin-right: 10px;
            font-weight: bold;
        }

        .filter-item select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 150px;
        }

        .schedule-table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .schedule-table th {
            background-color: #f2f2f2;
            border: 1px solid #ddd;
            padding: 12px;
            text-align: center;
        }

        .schedule-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
            height: 100px;
            vertical-align: top;
        }

        .schedule-table td.empty {
            background-color: #f9f9f9;
        }

        .schedule-table .date {
            font-weight: bold;
            margin-bottom: 5px;
            text-align: right;
        }

        .schedule-table .content {
            font-size: 12px;
            text-align: left;
        }

        .schedule-entry {
            margin-bottom: 5px;
            padding: 3px 5px;
            border-radius: 3px;
            background-color: #e6f7ff;
            border-left: 3px solid var(--primary-color);
            overflow: hidden; /* 避免内容溢出 */
            text-overflow: ellipsis; /* 显示省略号 */
            white-space: nowrap; /* 不换行 */
            font-weight: bold;
        }

        .employees-list {
            margin-top: 2px;
            margin-bottom: 8px;
            padding-left: 5px;
            font-size: 11px;
            color: #666;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .btn-refresh {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-refresh:hover {
            opacity: 0.9;
        }

        .inactive-entry {
            background-color: #ffe6e6;
            border-left: 3px solid #ff4d4f;
            text-decoration: line-through;
            opacity: 0.7;
        }
    </style>
    <script>
        let currentDate = new Date();
        let currentYear = currentDate.getFullYear();
        let currentMonth = currentDate.getMonth() + 1;
        let selectedDepartment = '';

        // 加载排班数据
        async function loadScheduleData() {
            try {
                // 获取选中的月份和部门
                const month = document.getElementById('month-select').value;
                const department = document.getElementById('department-select').value;

                // 更新当前年月和部门
                currentMonth = parseInt(month);
                selectedDepartment = department !== 'all' ? department : '';

                let url = `http://localhost:8080/api/schedules/month/${currentYear}/${currentMonth}`;
                if (selectedDepartment) {
                    url += `/department/${selectedDepartment}`;
                }

                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('获取排班数据失败');
                }

                const schedules = await response.json();

                // 获取每个排班记录对应的员工姓名
                for (let i = 0; i < schedules.length; i++) {
                    const schedule = schedules[i];
                    try {
                        // 使用工号搜索员工信息
                        const personResponse = await fetch(`http://localhost:8080/api/persons/search?keyword=${schedule.jobNumber}`);
                        if (personResponse.ok) {
                            const persons = await personResponse.json();
                            // 因为使用工号搜索，应该只会返回一个匹配的人员
                            if (persons && persons.length > 0) {
                                schedules[i].employeeName = persons[0].name || '未知';
                            } else {
                                schedules[i].employeeName = '未知';
                            }
                        }
                    } catch (error) {
                        console.error(`获取员工 ${schedule.jobNumber} 信息失败:`, error);
                        schedules[i].employeeName = '未知';
                    }
                }

                displaySchedules(schedules);
            } catch (error) {
                console.error('加载排班数据出错:', error);
                alert('加载排班数据失败，请稍后重试');
            }
        }

        // 显示排班数据
        function displaySchedules(schedules) {
            const calendarBody = document.getElementById('calendarBody');
            calendarBody.innerHTML = '';

            const firstDay = new Date(currentYear, currentMonth - 1, 1);
            const lastDay = new Date(currentYear, currentMonth, 0);
            const daysInMonth = lastDay.getDate();
            const startingDay = firstDay.getDay();

            let date = 1;
            for (let i = 0; i < 6; i++) {
                const row = document.createElement('tr');

                for (let j = 0; j < 7; j++) {
                    const cell = document.createElement('td');

                    if (i === 0 && j < startingDay) {
                        cell.classList.add('empty');
                    } else if (date > daysInMonth) {
                        cell.classList.add('empty');
                    } else {
                        // 添加日期
                        const dateDiv = document.createElement('div');
                        dateDiv.classList.add('date');
                        dateDiv.textContent = date;
                        cell.appendChild(dateDiv);

                        // 添加内容容器
                        const contentDiv = document.createElement('div');
                        contentDiv.classList.add('content');

                        // 根据传入的schedules数据填充
                        const currentDate = new Date(currentYear, currentMonth - 1, date);
                        const currentDateStr = currentDate.toISOString().split('T')[0]; // 格式：YYYY-MM-DD

                        // 筛选当天的排班记录
                        const daySchedules = schedules.filter(schedule => {
                            const scheduleDate = new Date(schedule.scheduleTime);
                            return scheduleDate.getDate() === date &&
                                scheduleDate.getMonth() === currentMonth - 1 &&
                                scheduleDate.getFullYear() === currentYear;
                        });

                        // 按部门分组显示排班
                        const departmentSchedules = {};
                        daySchedules.forEach(schedule => {
                            if (!departmentSchedules[schedule.department]) {
                                departmentSchedules[schedule.department] = [];
                            }
                            departmentSchedules[schedule.department].push(schedule);
                        });

                        // 为每个部门创建排班条目
                        Object.keys(departmentSchedules).forEach(department => {
                            const departmentDiv = document.createElement('div');
                            departmentDiv.classList.add('schedule-entry');

                            // 显示部门名称和人数
                            departmentDiv.textContent = department + ': ' +
                                departmentSchedules[department].length + '人';
                            contentDiv.appendChild(departmentDiv);

                            // 为每个部门添加员工姓名列表
                            const employeesList = document.createElement('div');
                            employeesList.classList.add('employees-list');

                            // 获取该部门当天的所有员工姓名
                            const employees = departmentSchedules[department].map(schedule =>
                                schedule.employeeName || '未知');

                            // 显示员工姓名（最多显示3个，超过则显示省略号）
                            if (employees.length <= 3) {
                                employeesList.textContent = employees.join(', ');
                            } else {
                                employeesList.textContent = employees.slice(0, 3).join(', ') + '...';
                            }

                            contentDiv.appendChild(employeesList);
                        });

                        cell.appendChild(contentDiv);
                        date++;
                    }

                    row.appendChild(cell);
                }

                calendarBody.appendChild(row);
                if (date > daysInMonth) break;
            }
        }

        // 获取指定日期的排班信息
        function getScheduleForDate(schedules, date) {
            const scheduleDate = new Date(currentYear, currentMonth - 1, date);
            const scheduleForDate = schedules.filter(s =>
                new Date(s.scheduleDate).toDateString() === scheduleDate.toDateString()
            );

            return scheduleForDate.map(s => `
                <div class="schedule-item">
                    <span class="employee-name">${s.personId}</span>
                    <span class="shift-type">${s.shiftType}</span>
                </div>
            `).join('');
        }

        // 切换月份
        function changeMonth(delta) {
            currentMonth += delta;
            if (currentMonth > 12) {
                currentMonth = 1;
                currentYear++;
            } else if (currentMonth < 1) {
                currentMonth = 12;
                currentYear--;
            }
            // 更新月份选择框
            document.getElementById('month-select').value = currentMonth;
            loadScheduleData();
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            var menuItems = document.querySelectorAll('.menu-item > a');
            menuItems.forEach(function (item) {
                item.addEventListener('click', function (e) {
                    var parent = item.parentElement;
                    // 只允许单开一个折叠区
                    document.querySelectorAll('.menu-item').forEach(function (el) {
                        if (el !== parent) el.classList.remove('active');
                    });
                    parent.classList.toggle('active');
                    e.preventDefault();
                });
            });

            // 添加首页链接的点击事件
            document.querySelector('.menu-item:first-child > a').addEventListener('click', function (e) {
                e.preventDefault(); // 阻止默认行为
                window.location.href = '../homepage/manager_home.html'; // 跳转到管理员首页
            });

            // 默认展开人员管理菜单
            const personMenuItem = document.querySelector('.menu-item:nth-child(2)');
            if (personMenuItem) {
                personMenuItem.classList.add('active');
            }

            // 设置月份选择框为当前月份
            const currentMonthValue = new Date().getMonth() + 1;
            document.getElementById('month-select').value = currentMonthValue;

            // 生成日历框架
            const year = currentYear;
            const month = currentMonth;
            const daysInMonth = new Date(year, month, 0).getDate();
            const firstDayOfMonth = new Date(year, month - 1, 1).getDay();
            generateCalendar(year, month, daysInMonth, firstDayOfMonth);

            // 加载排班数据
            loadScheduleData();

            // 绑定筛选事件
            document.getElementById('month-select').addEventListener('change', loadScheduleData);
            document.getElementById('department-select').addEventListener('change', loadScheduleData);
            document.getElementById('refresh-btn').addEventListener('click', loadScheduleData);
        });



        // 生成日历表格框架
        function generateCalendar(year, month, daysInMonth, firstDayOfMonth) {
            const calendarBody = document.getElementById('calendarBody');
            calendarBody.innerHTML = '';

            let dayCounter = 1;

            // 计算需要多少行
            let numRows = Math.ceil((daysInMonth + firstDayOfMonth) / 7);

            for (let i = 0; i < numRows; i++) {
                let row = document.createElement('tr');

                for (let j = 0; j < 7; j++) {
                    let cell = document.createElement('td');

                    if ((i === 0 && j < firstDayOfMonth) || dayCounter > daysInMonth) {
                        // 空单元格
                        cell.classList.add('empty');
                    } else {
                        // 创建日期显示
                        let dateDiv = document.createElement('div');
                        dateDiv.className = 'date';
                        dateDiv.textContent = dayCounter;

                        // 创建内容容器
                        let contentDiv = document.createElement('div');
                        contentDiv.className = 'content';
                        contentDiv.id = `day-${dayCounter}`;

                        cell.appendChild(dateDiv);
                        cell.appendChild(contentDiv);

                        dayCounter++;
                    }

                    row.appendChild(cell);
                }

                calendarBody.appendChild(row);
            }
        }

        function logout() {
            // 添加确认提示
            if (confirm('确定要退出登录吗？')) {
                // 清除本地存储的登录信息
                localStorage.removeItem('userInfo');
                localStorage.removeItem('token');

                // 跳转到登录页面
                window.location.href = '../../login.html';
            }
        }
    </script>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">部门经理</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="homepage/manager_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">👥</span>
                    <span class="menu-title">人员管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../person/person_list.html">人员列表</a></li>
                    <li><a href="../person/person_edit.html">添加人员</a></li>
                    <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                    <li><a href="../person/schedule.html" class="active">查看排班表</a></li>
                    <li><a href="../person/schedule_statistics.html">班次统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                    <li><a href="*">物料采购统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                    <li><a href="*">设备报修报废统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_list.html">产品列表</a></li>
                    <li><a href="../product/editproduct_plan.html">编辑生产计划</a></li>
                    <li><a href="../product/viewproduct_plan.html">查看生产计划</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>
    <!-- 主内容区域 -->
    <main class="admin-main">
        <h1>排班表管理</h1>

        <!-- 筛选条件 -->
        <div class="filter-container">
            <div class="filter-item">
                <label for="month-select">月份:</label>
                <select id="month-select">
                    <option value="1">1月</option>
                    <option value="2">2月</option>
                    <option value="3">3月</option>
                    <option value="4">4月</option>
                    <option value="5">5月</option>
                    <option value="6">6月</option>
                    <option value="7">7月</option>
                    <option value="8">8月</option>
                    <option value="9">9月</option>
                    <option value="10">10月</option>
                    <option value="11">11月</option>
                    <option value="12">12月</option>
                </select>
            </div>

            <div class="filter-item">
                <label for="department-select">部门:</label>
                <select id="department-select">
                    <option value="all">全部部门</option>
                    <option value="表面处理车间">表面处理车间</option>
                    <option value="锻压车间">锻压车间</option>
                    <option value="组装车间">组装车间</option>
                    <option value="质检车间">质检车间</option>
                    <option value="机加车间">机加车间</option>
                </select>
            </div>

            <button id="refresh-btn" class="btn-refresh">刷新</button>
        </div>

        <!-- 排班表 -->
        <div class="schedule-container">
            <table class="schedule-table">
                <thead>
                <tr>
                    <th>周日</th>
                    <th>周一</th>
                    <th>周二</th>
                    <th>周三</th>
                    <th>周四</th>
                    <th>周五</th>
                    <th>周六</th>
                </tr>
                </thead>
                <tbody id="calendarBody">
                <!-- 日历内容将通过JavaScript动态生成 -->
                </tbody>
            </table>
        </div>
    </main>
</div>
</body>
</html>